<template>
  <div class="monthly-summary">
    <!-- 报表主体内容 -->
    <el-card shadow="hover" class="main-card">
      <!-- 汇总指标卡片 -->
      <div class="metric-cards">
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="月销售额" 
              :value="formatCurrency(reportData.totalSales || 0)" 
              icon="Money"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="订单数量" 
              :value="reportData.orderCount || 0" 
              icon="Document"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="日均销售" 
              :value="formatCurrency(getDailyAverage)" 
              icon="DataAnalysis"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="报表月份" 
              :value="formatMonth(reportData.year, reportData.month)" 
              icon="Calendar"
            />
          </el-col>
        </el-row>
      </div>

      <!-- 每日销售趋势图 -->
      <div class="chart-section">
        <h3>每日销售趋势</h3>
        <div ref="dailyChart" class="chart-container"></div>
      </div>

      <!-- 支付方式统计 -->
      <div class="payment-section" v-if="reportData.paymentMethods && reportData.paymentMethods.length > 0">
        <h3>支付方式统计</h3>
        <el-table :data="reportData.paymentMethods" stripe>
          <el-table-column prop="method" label="支付方式" min-width="120">
            <template #default="scope">
              <el-tag :type="getPaymentMethodType(scope.row.method)">
                {{ getPaymentMethodName(scope.row.method) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" min-width="120">
            <template #default="scope">
              <span class="amount-text">{{ formatCurrency(scope.row.amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="笔数" min-width="80" />
          <el-table-column label="占比" min-width="120">
            <template #default="scope">
              <el-progress 
                :percentage="getPaymentPercentage(scope.row.amount)" 
                :color="getPaymentColor(scope.row.method)"
                :stroke-width="10"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 渠道销售统计 -->
      <div class="channel-section" v-if="reportData.channelSales && reportData.channelSales.length > 0">
        <h3>渠道销售统计</h3>
        <el-table :data="reportData.channelSales" stripe>
          <el-table-column prop="channelName" label="销售渠道" min-width="120" />
          <el-table-column prop="amount" label="销售额" min-width="120">
            <template #default="scope">
              <span class="amount-text">{{ formatCurrency(scope.row.amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orders" label="订单数" min-width="80" />
          <el-table-column label="占比" min-width="120">
            <template #default="scope">
              <el-progress 
                :percentage="getChannelPercentage(scope.row.amount)" 
                :color="getChannelColor(scope.row.channelName)"
                :stroke-width="10"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 热销商品TOP10 -->
      <div class="top-products-section" v-if="reportData.topProducts && reportData.topProducts.length > 0">
        <h3>热销商品TOP10</h3>
        <el-table :data="reportData.topProducts.slice(0, 10)" stripe>
          <el-table-column type="index" label="排名" width="60" />
          <el-table-column prop="productName" label="商品名称" min-width="150" />
          <el-table-column prop="quantity" label="销量" min-width="80" />
          <el-table-column prop="amount" label="销售额" min-width="120">
            <template #default="scope">
              <span class="amount-text">{{ formatCurrency(scope.row.amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="占比" min-width="120">
            <template #default="scope">
              <el-progress 
                :percentage="getProductPercentage(scope.row.amount)" 
                :color="getRandomColor(scope.row.productName)"
                :stroke-width="10"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 报表说明 -->
      <div class="note-content compact-note">
        <el-tag type="info" effect="plain" size="small">
          <i class="el-icon-info"></i> 本报表显示 {{ formatMonth(reportData.year, reportData.month) }} 的销售数据汇总
        </el-tag>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import * as echarts from 'echarts';
import MetricCard from './common/MetricCard.vue';

const props = defineProps({
  reportData: {
    type: Object,
    default: () => ({})
  },
  dateRange: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
});

const dailyChart = ref(null);
let chartInstance = null;

// 计算日均销售额
const getDailyAverage = computed(() => {
  if (!props.reportData.dailySales || props.reportData.dailySales.length === 0) {
    return 0;
  }
  const totalSales = props.reportData.totalSales || 0;
  const daysInMonth = props.reportData.dailySales.length;
  return daysInMonth > 0 ? totalSales / daysInMonth : 0;
});

// 格式化货币
const formatCurrency = (amount) => {
  return `¥${Number(amount || 0).toFixed(2)}`;
};

// 格式化月份
const formatMonth = (year, month) => {
  if (!year || !month) return '未知月份';
  return `${year}年${month}月`;
};

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  const names = {
    'cash': '现金',
    'wechat': '微信支付',
    'alipay': '支付宝',
    'card': '银行卡',
    'mixed': '混合支付'
  };
  return names[method] || method;
};

// 获取支付方式类型
const getPaymentMethodType = (method) => {
  const types = {
    'cash': 'success',
    'wechat': 'primary',
    'alipay': 'warning',
    'card': 'info',
    'mixed': 'danger'
  };
  return types[method] || '';
};

// 获取支付方式颜色
const getPaymentColor = (method) => {
  const colors = {
    'cash': '#67C23A',
    'wechat': '#409EFF',
    'alipay': '#E6A23C',
    'card': '#909399',
    'mixed': '#F56C6C'
  };
  return colors[method] || '#409EFF';
};

// 获取渠道颜色
const getChannelColor = (channelName) => {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'];
  const hash = channelName.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  return colors[Math.abs(hash) % colors.length];
};

// 获取随机颜色
const getRandomColor = (str) => {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#C71585', '#FF6347', '#32CD32'];
  const hash = str.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  return colors[Math.abs(hash) % colors.length];
};

// 计算支付方式占比
const getPaymentPercentage = (amount) => {
  const total = props.reportData.totalSales || 0;
  return total > 0 ? Math.round((amount / total) * 100) : 0;
};

// 计算渠道占比
const getChannelPercentage = (amount) => {
  const total = props.reportData.totalSales || 0;
  return total > 0 ? Math.round((amount / total) * 100) : 0;
};

// 计算商品占比
const getProductPercentage = (amount) => {
  const total = props.reportData.totalSales || 0;
  return total > 0 ? Math.round((amount / total) * 100) : 0;
};

// 初始化每日销售趋势图
const initDailyChart = () => {
  if (!dailyChart.value || !props.reportData.dailySales) return;

  if (chartInstance) {
    chartInstance.dispose();
  }

  chartInstance = echarts.init(dailyChart.value);

  const option = {
    title: {
      text: '每日销售趋势',
      left: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0];
        return `${data.name}日<br/>销售额: ¥${data.value.toFixed(2)}<br/>订单数: ${props.reportData.dailySales[data.dataIndex].orders}`;
      }
    },
    xAxis: {
      type: 'category',
      data: props.reportData.dailySales.map(item => item.day + '日')
    },
    yAxis: {
      type: 'value',
      name: '销售额(元)',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [{
      data: props.reportData.dailySales.map(item => item.amount),
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      },
      itemStyle: {
        color: '#409EFF'
      }
    }]
  };

  chartInstance.setOption(option);
};

// 监听报表数据变化
watch(() => props.reportData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    nextTick(() => {
      initDailyChart();
    });
  }
}, { deep: true });

// 组件挂载时初始化图表
onMounted(() => {
  nextTick(() => {
    initDailyChart();
  });
});
</script>

<style scoped>
.monthly-summary {
  margin-bottom: 20px;
}

.main-card {
  margin-bottom: 20px;
}

.metric-cards {
  margin-bottom: 30px;
}

.chart-section,
.payment-section,
.channel-section,
.top-products-section {
  margin-bottom: 30px;
}

.chart-section h3,
.payment-section h3,
.channel-section h3,
.top-products-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.amount-text {
  font-weight: 600;
  color: #E6A23C;
}

.note-content {
  margin-top: 20px;
  text-align: center;
}

.compact-note {
  margin-top: 15px;
}
</style>
